package com.practice.reggie.service.impl.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.practice.reggie.common.CustomException;
import com.practice.reggie.dto.SetmealDto;
import com.practice.reggie.entity.Setmeal;
import com.practice.reggie.entity.SetmealDish;
import com.practice.reggie.mapper.SetmealMapper;
import com.practice.reggie.service.SetmealDishService;
import com.practice.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 套餐保存
     * @param setmealDto
     */
    @Override
    public void saveAndSetmDish(SetmealDto setmealDto) {
        //保存主表信息
        save(setmealDto);
        //取套餐id
        Long setmealId = setmealDto.getId();
        //取套餐关联菜品
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = dishes.stream().map(item -> {
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        //保存
        setmealDishService.saveBatch(collect);
    }

    /**
     * 套餐批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，判断是否删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if(count > 0){
            //2.1如果不能删除，抛出一个业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //2.2如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(ids);
        //删除关系表数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId,ids);
        //删除
        setmealDishService.remove(wrapper);
    }

    /**
     * 套餐详情展示
     * @param id
     * @return
     */
    @Override
    public SetmealDto getByIdWithDish(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(setmealDishList);
        return setmealDto;
    }
}
